rm(list = ls())
load("data/icews_matrix.RData")

library(amen)
## run three AME models
yearmonths <- sort(names(icews_matrix))

results <- names(icews_matrix)
AME_score <- list()

for (i in 1:length(names(icews_matrix))){
  AME_score[[i]] = ame(
    Y = as.matrix(icews_matrix[[i]]), 
    symmetric= FALSE, 
    rvar=TRUE,
    cvar = TRUE,
    R=1, 
    model = "nrm",
    #family='nrm', 
    intercept=TRUE, seed=6886,
    burn= 5000, nscan= 20000, odens=20,
    plot=FALSE, gof=TRUE)
  print(i)
}

names(AME_score) <- names(icews_matrix)
save(AME_score, file = "data/AME_score.RData")


load("data/AME_score.RData")
library(purrr)
library(reshape)
library(dplyr)
# create a list to store the data
ame_df <- list()

for (i in seq_along(AME_score)){
#extract the model results
m <-  AME_score[[i]]
# get a name of the model
yearmonth <- names(AME_score)[i]

l <- melt(m$UVPM) 
names(l) <- c("iso_a", "iso_b", "latent_score")

l$iso_a <- as.character(l$iso_a )
l$iso_b <- as.character(l$iso_b)

l <- l %>% 
  dplyr::mutate(latent_score = ifelse(iso_a == iso_b, NA, latent_score)) %>% 
  rowwise() %>% 
  dplyr::mutate(yearmonth = yearmonth)

ame_df[[i]] <- l
}
names(ame_df) <- names(AME_score)

ame_df_icews <- do.call(rbind, ame_df)
ame_df_icews$year <- substr(ame_df_icews$yearmonth,1, 4)
ame_df_icews$month <- substr(ame_df_icews$yearmonth,5, 6)
ame_df_icews$year <- as.integer(ame_df_icews$year)
ame_df_icews$month <- as.integer(ame_df_icews$month)
save(ame_df_icews, file = "data/ame_df_icews.RData")
